package com.itmuch.box.core.xss;

import java.beans.PropertyEditorSupport;

import org.apache.commons.lang.StringEscapeUtils;

public class StringEscapeEditor extends PropertyEditorSupport {
    private boolean escapeHTML;
    private boolean escapeJavaScript;
    private boolean escapeSQL;
    private boolean escapeXML;

    public StringEscapeEditor() {
        super();
    }

    public StringEscapeEditor(boolean escapeHTML, boolean escapeJavaScript, boolean escapeSQL, boolean escapeXML) {
        super();
        this.escapeHTML = escapeHTML;
        this.escapeJavaScript = escapeJavaScript;
        this.escapeSQL = escapeSQL;
        this.escapeXML = escapeXML;
    }

    @Override
    public void setAsText(String text) {
        if (text == null) {
            this.setValue(null);
        } else {
            if (this.escapeHTML) {
                text = StringEscapeUtils.escapeHtml(text);
            }
            if (this.escapeJavaScript) {
                text = StringEscapeUtils.escapeJavaScript(text);
            }
            if (this.escapeSQL) {
                text = StringEscapeUtils.escapeSql(text);
            }
            if (this.escapeXML) {
                text = StringEscapeUtils.escapeXml(text);
            }
            this.setValue(text);
        }
    }

    @Override
    public String getAsText() {
        Object value = this.getValue();
        return value != null ? value.toString() : "";
    }
}